<template>
  <div class="chat-wrapper">
    <!-- 主聊天区域 (带边框) -->
    <div class="chat-container">
      <!-- 左侧联系人列表 (带边框) -->
      <div class="contact-list">
        <div class="contact-header">联系列表</div>
        <el-scrollbar class="contact-scroll">
          <div class="contact-item" v-for="(user, index) in contactList" :key="user.id"
            :class="{ active: receiverId === user.id }" @click="selectContact(user)">
            <img :src="user.avatar"  v-if="user.avatar" style="width: 40px; height: 40px; border-radius: 4px;">
            <div class="contact-avatar" v-else>{{ user.username.charAt(0) }}</div>
            <div class="contact-info">
              <div class="contact-name">{{ user.username }}</div>
            </div>
          </div>
        </el-scrollbar>
      </div>

      <!-- 右侧聊天区域 (带边框) -->
      <div class="chat-area">
        <div v-if="receiverId === null" class="empty-tip">
          <div class="empty-text">请选择联系人开始聊天</div>
        </div>
        <template v-else>
          <el-scrollbar class="message-scroll" ref="messageScroll">
            <div class="message-container" ref="messageContainer">
              <template v-for="(msg, index) in contentMsg" :key="index">
                <!-- 自己发送的消息 -->
                <div class="message self" v-if="msg.senderId === currentId">
                  <div class="message-content" style="text-align: left;">
                    {{ msg.content }}
                  </div>
                  <div class="message-time">{{ msg.sendTime }}</div>
                </div>
                <!-- 其他人发送的消息 -->
                <div class="message other" v-else>
                  <div class="message-content">{{ msg.content }}</div>
                  <div class="message-time">{{ msg.sendTime }}</div>
                </div>
              </template>
            </div>
          </el-scrollbar>
          
          <div class="input-area">
            <el-input
              v-model="inputMessage"
              class="messageInput"
              placeholder="输入消息..."
              @keyup.enter="sendMessage"
            ></el-input>
            <el-button 
              type="primary" 
              @click="sendMessage"
              class="send-btn"
            >
              发送
            </el-button>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup> 
import { ref, onMounted, onUnmounted, nextTick, h } from 'vue'
import { getContactApi, getHistoryMsgApi, isContactApi }  from '../../api/jobSeeker'
import { ElMessage, ElMessageBox } from 'element-plus'

// 联系人数据列表
const contactList = ref([])
// 消息
const contentMsg = ref([])
const inputMessage = ref('') //  输入的消息
// 获取滚动条和容器引用
const messageScroll = ref(null)
const messageContainer = ref(null)
let websocket = null;
const currentId = ref(null)
const receiverId = ref(null)

onMounted(() => {
  console.log('组件已挂载')
  getInfo()
  isContact()
  initWebSocket()
})
onUnmounted(() => {
  console.log('组件已卸载')
  websocket.close()
})
//从本地获取当前用户id
const getInfo = () => {
  const user = JSON.parse(localStorage.getItem('jobseekerInfo'))
  if (user && user.id) {
    currentId.value = user.id
  }
}
//查询联系人
const queryContact = async () => {
  const result = await getContactApi(currentId.value)
  if (result.code){
    contactList.value = result.data
  }else{
    ElMessage.error(result.message)
  }
}
// 选择联系人
const selectContact = async (user) => {
  receiverId.value = user.id
  const result = await getHistoryMsgApi(user.id)
  if (result.code){
    contentMsg.value = result.data
  }else{
    ElMessage.error(result.message)
  }
  // 确保DOM更新后滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
}
// 初始化WebSocket连接
const initWebSocket = () => {
  websocket = new WebSocket('ws://localhost:8080/ws/' + currentId.value);
  //连接成功建立的回调方法
  websocket.onopen = () => {
    console.log("连接成功");
  }
  //连接发生错误的回调方法
  websocket.onerror = (error) => {
    console.error("WebSocket错误:", error);
  };
  //接收到消息的回调方法
  websocket.onmessage = (event) => {
    console.log('收到消息:' + event.data)
    const msgObj = JSON.parse(event.data)
    //如果当前打开的聊天页面与发送者id相同，则将消息添加到聊天记录中
    if (msgObj.senderId == receiverId.value) {
      //将时间设置为2022-02-02 13:23:30格式
     msgObj.sendTime = new Date(msgObj.sendTime).toLocaleString()
      contentMsg.value.push({
        senderId: msgObj.senderId,
        content: msgObj.content,
        sendTime: msgObj.sendTime
      })
      // 确保DOM更新后滚动到底部
      nextTick(() => {
        scrollToBottom()
      })
    }
  };
}
//发送信息
const sendMessage = () => { 
  if(!inputMessage.value)  return
  console.log('发送消息:' +  inputMessage.value)
  contentMsg.value.push({
    senderId: currentId.value,
    content: inputMessage.value,
    sendTime: new Date().toLocaleString()
  })
  // 确保DOM更新后滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
  const msgObj = {
    senderId: currentId.value,
    receiverId: receiverId.value,
    message: inputMessage.value,
  };
  websocket.send(JSON.stringify(msgObj))
  inputMessage.value = ''
}
//发送默认信息
const sendDefaultMessage = (hrId) => {
  const defaultMessage = "您好，很高兴与您沟通，希望能进一步交流这个职位"
  contentMsg.value.push({
    senderId: currentId.value,
    content: defaultMessage,
    sendTime: new Date().toLocaleString()
  })
  // 确保DOM更新后滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
  const msgObj = {
    senderId: currentId.value,
    receiverId: hrId,
    message: defaultMessage,
  };
  websocket.send(JSON.stringify(msgObj))
}
//判断是否为联系人
const isContact = async () => {
  // 从本地存储获取目标HR ID
  let targetHrId = localStorage.getItem('targetHrId')
  if(targetHrId){
    targetHrId = Number(targetHrId)
    receiverId.value = targetHrId
    // 判断是否为联系人
    const result = await isContactApi(targetHrId)
    if(result.code){
      //如果是第一次聊天，则为双方建立好友关系并发送默认消息
      if(!result.data || result.data === 0){
        console.log('第一次聊天')
        sendDefaultMessage(targetHrId)
      }else{
        // 不是第一次聊天，则获取聊天记录
        const historyMes = await getHistoryMsgApi(targetHrId)
        console.log(historyMes.data)
        if(historyMes.code){
          contentMsg.value = historyMes.data
        }else{
          ElMessage.error(historyMes.message)
        }
          // 确保DOM更新后滚动到底部
          nextTick(() => {
            scrollToBottom()
          })
      }
    }else{
      ElMessage.error(result.message)
    }
    // 清除存储的HR ID
    localStorage.removeItem('targetHrId')
  }
  // 查询联系人列表
  queryContact()
}
// 滚动到底部
const scrollToBottom = () => {
  if (messageScroll.value && messageContainer.value) {
    const scrollbar = messageScroll.value.wrapRef
    scrollbar.scrollTop = messageContainer.value.scrollHeight
  }
}
</script>

<style scoped>
/* 整体布局 */
.chat-wrapper {
  height: 650px;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
/* 主聊天容器 (带边框) */
.chat-container {
  display: flex;
  flex: 1;
  overflow: hidden;
  border: 1px solid #e6e6e6; /* 添加外层边框 */
  border-radius: 4px;
  margin: 10px;
}

/* 左侧联系人列表 (带边框) */
.contact-list {
  width: 240px;
  border-right: 1px solid #e6e6e6; /* 添加右侧边框 */
  display: flex;
  flex-direction: column;
}

.contact-header {
  padding: 15px;
  font-weight: bold;
  border-bottom: 1px solid #e6e6e6;
}

.contact-scroll {
  flex: 1;
  overflow-y: auto;
}

.contact-item {
  display: flex;
  padding: 12px;
  cursor: pointer;
  border-bottom: 1px solid #f5f5f5;
  transition: background-color 0.2s;
}

.contact-item:hover {
  background-color: #f5f5f5;
}

.contact-item.active {
  background-color: #e6f7ff;
}

.contact-avatar {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  background-color: #95ec69;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  font-size: 16px;
}

.contact-info {
  flex: 1;
  min-width: 0;
}

.contact-name {
  font-weight: 500;
  margin-top: 8px;
  margin-left: 10px;
}


/* 右侧聊天区域 (带边框) */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #e6e6e6; /* 添加左侧边框 */
}

.empty-tip {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 16px;
    width: 800px;
}

.message-scroll {
  width: 800px;
  flex: 1;
  overflow-y: auto;
}

.message-container {
  padding: 15px;
}

/* 消息排列修正 (完全按照图片) */
.message {
  margin-bottom: 15px;
  max-width: 100%;
  display: block; /* 改为块级元素确保垂直排列 */
}

.message.other {
  text-align: left;
}

.message.self {
  text-align: right;
}

.message-content {
  padding: 10px 15px;
  border-radius: 4px;
  display: inline-block;
  max-width: 70%;
  word-break: break-word;
  line-height: 1.5;
}

.message.other .message-content {
  background-color: #f0f0f0;
}

.message.self .message-content {
  background-color: #95ec69;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

/* 输入区域 */
.input-area {
  padding: 15px;
  border-top: 1px solid #e6e6e6;
  display: flex;
  gap: 10px;
}

.input-area .el-input {
  flex: 1;
}

.send-btn {
  width: 80px;
}
</style>